package com.gest.util;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class FilterComboBox extends JComboBox {
	private List<String> array;
	private JTextField textfield = new JTextField();
	private String focusSel = null;

	public FilterComboBox(List<String> array) {
		super(array.toArray());
		this.array = array;
		this.setEditable(true);
		textfield = (JTextField) this.getEditor().getEditorComponent();
		textfield.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent ke) {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						comboFilter(textfield.getText());
					}
				});
			}
		});
		this.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				focusSel = textfield.getText();
			}
		});
	}

	public void comboFilter(String enteredText) {
		List<String> filterArray = new ArrayList<String>();
		for (int i = 0; i < array.size(); i++) {
			if (array.get(i).toLowerCase().contains(enteredText.toLowerCase())) {
				filterArray.add(array.get(i));
			}
		}
		if (filterArray.size() > 0) {
			this.setModel(new DefaultComboBoxModel(filterArray.toArray()));
			this.setSelectedItem(enteredText);
			this.showPopup();
		} else {
			this.hidePopup();
		}
	}

	public void RemplireComboListe(List<String> strings) {
		array = strings;
		this.setModel(new DefaultComboBoxModel(array.toArray()));
	}

	public List<String> getArray() {
		return array;
	}

	public void setArray(List<String> array) {
		this.array = array;
	}

	public JTextField getTextfield() {
		return textfield;
	}

	public void setTextfield(JTextField textfield) {
		this.textfield = textfield;
	}

	public String getFocusSel() {
		return focusSel;
	}

	public void setFocusSel(String focusSel) {
		this.focusSel = focusSel;
	}

}